/*******************************************************************************
 * Copyright (c) 2014 Francesco Gabbrielli
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Francesco Gabbrielli - initial API and implementation
 ******************************************************************************/
package it.francescogabbrielli.android.solidalapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

/**
 * Receiver for {@link ActionService}
 * 
 * XXX: update ALWAYS manifest for intent filter...
 */
public class ActionReceiver extends BroadcastReceiver {
	
	@Override
	public void onReceive(Context context, Intent intent) {
		
		try {
			
			SolidalApp app = (SolidalApp) context.getApplicationContext();
			
			@SuppressWarnings("unchecked")
			Class<? extends Action> actionClass = (Class<? extends Action>) 
					Class.forName(getClass().getPackage().getName()+".actions."+intent.getAction());
					
			try {
				Action action = app.getAction(actionClass);
				if (action!=null) {
					action.init(context, intent);
				} else {
					Log.w(SolidalApp.TAG, "Action expired: "+actionClass);
					return;
				}
				if (intent.hasExtra(Constants.ERROR))
					action.onError(intent.getStringExtra(Constants.ERROR));
				else
					action.onPostExecute();
			} catch(Exception e) {
				Log.e(SolidalApp.TAG+" "+actionClass.getSimpleName(), "Receiver Error", e);
			} finally {
				app.removeAction(actionClass);
			}
			
		} catch(ClassNotFoundException e) {
			Log.w(SolidalApp.TAG, "No action for: "+this);			
		}
		
		Bundle extras = intent.getExtras();
	
		Log.i(SolidalApp.TAG, "Endpoints receiving: "+intent.getAction());
		Log.v(SolidalApp.TAG, "Extras: "+EndpointsUtils.toString(extras));
				
	}
}
